package com.sgj.gulimall.ssoserver.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @Author: Guoji Shen
 * @Date: 2021/9/10 9:53
 */
@Controller
public class LoginController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @ResponseBody
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("token") String token) {
        return redisTemplate.opsForValue().get(token);
    }

    @GetMapping("/login.html")
    public String loginPage(@RequestParam("redirect_url") String url, Model model,
                            @CookieValue(value = "sso_token", required = false) String token) {
        if (StringUtils.isNotBlank(token)) {
            // 已在其他地方登陆过，直接免登录跳转
            return "redirect:" + url + "?token=" + token;
        }
        model.addAttribute("url", url);
        return "login";
    }

    @PostMapping("/doLogin")
    public String doLogin(@RequestParam("username") String username, @RequestParam("password") String password,
                          @RequestParam("url") String url, HttpServletResponse response) {
        // 简单验证
        if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) {
            String uuid = UUID.randomUUID().toString().replace("-", "");
            redisTemplate.opsForValue().set(uuid, username);
            Cookie token = new Cookie("sso_token", uuid);
            response.addCookie(token);
            // 登陆成功跳转，跳回之前的页面
            return "redirect:" + url + "?token=" + uuid;
        }
        // 登陆失败
        return "login";
    }
}